import { getWxAccessToken, getWxVertifyResult } from './dependence'
Page({
  data: {
    action: "",
    location: "",
    params: ""
  },
  onLoad: function (options) {
    const { action = "", location = "", params = "" } = options
    this.setData({
      action,
      location,
      params: params ? JSON.parse(params) : {}
    })
  },
  onReady() {
    setTimeout(() => {
      if (this.data.action == 'authFace') {
        this.initAuthFace()
      } else if (this.data.action == 'scan') {
        this.initScanner()
      }
    }, 500)
  },
  initAuthFace() {
    const { name = "", cardId = "", mobile = "" } = this.data.params
    wx.startFacialRecognitionVerify({
      name: name,//身份证名称
      idCardNumber: cardId,//身份证号码
      success: async (res) => {
        try {
          const access_token = await getWxAccessToken(),
            { verifyResult } = res
          await getWxVertifyResult(access_token, verifyResult)
          this.changePrePage({
            action: 'authFace',
            msg: '用户认证成功',
            code: '200'
          })
        } catch (msg) {
          this.changePrePage({
            action: 'authFace',
            msg: '用户认证失败，请重新认证'
          })
        }
      },
      checkAliveType: 2,//屏幕闪烁(人脸核验的交互方式，默认0,读数字)
      fail: () => {
        this.changePrePage({
          action: 'authFace',
          msg: '用户认证失败，请重新认证'
        })
      }
    })
  },
  initScanner() {
    wx.scanCode({
      scanType: ['qrCode'],
      success: (res) => {
        this.changePrePage({
          action: 'scan',
          code: '200',
          params: res.result
        })
      },
      fail: () => {
        this.changePrePage({
          action: 'scan',
          msg: '扫码失败，请重试',
        })
      }
    })
  },
  changePrePage({ action = "", msg = "", code = '', params = '' }) {
    let pages = getCurrentPages(),
      prevPage = pages[pages.length - 2]
    wx.navigateBack({
      success: () => {
        prevPage.transFormPageCallback({ url: this.data.location, action, msg, code, params })
      }
    })
  }
})